package aspect;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import pojo.Merchant;

@Component
@Aspect
public class LoginAspect {
	private final String p1 = "execution(* service.MerchantService.register(..))";
	private final String p2 = "execution(* service.MerchantService.login(..))";
	
	private final String p3 = "execution(* service.MerchantService.reRegister(..))";

	private MessageDigest digest;

	public LoginAspect() {
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	@Around(value = p1)
	public Object regist(ProceedingJoinPoint point) {
		Object o = null;

		Merchant merchant = (Merchant) point.getArgs()[0];
		merchant.setPassword(mdProceed(merchant.getPassword()));
		try {
			o = point.proceed(new Object[] { merchant });
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}

	@Around(value = p2)
	public Object login(ProceedingJoinPoint point) {
		Object o = null;

		Merchant merchant = (Merchant) point.getArgs()[0];
		String password = mdProceed(merchant.getPassword());
		merchant.setPassword(password);
		try {
			o = point.proceed(new Object[] { merchant });
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}
	
	@Around(value = p3)
	public Object reRegister(ProceedingJoinPoint point) {
		Object o = null;

		Merchant merchant = (Merchant) point.getArgs()[0];
		String password = mdProceed(merchant.getPassword());
		merchant.setPassword(password);
		try {
			o = point.proceed(new Object[] { merchant });
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}

	private String mdProceed(String s) {
		String ss = null;
		try {
			byte[] bs = digest.digest(s.getBytes("ISO-8859-1"));
			ss = new String(bs, "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return ss;
	}
}
